package com.lin.chapter8;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class ServerBootStrapGuideClient {
	public static void main(String[] args) {
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup())
				.channel(NioServerSocketChannel.class)
				.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
					ChannelFuture channelFuture;
					@Override
					public void channelActive(ChannelHandlerContext ctx) throws Exception {
						ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Client, I'm here", CharsetUtil.UTF_8));
						Bootstrap b = new Bootstrap();
						b.channel(NioSocketChannel.class)
								.handler(new SimpleChannelInboundHandler<ByteBuf>() {
									@Override
									protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
										System.out.println("Received data");
									}
								});
						b.group(ctx.channel().eventLoop());
						channelFuture = b.connect(new InetSocketAddress("www.baidu.com", 80));
						channelFuture.addListener(channelFuture -> {
							System.out.println("Connect Romote Addr");
						});
					}

					@Override
					protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
						System.out.println("Received from Client:" + byteBuf.toString(CharsetUtil.UTF_8));
					}
				});
		ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080));
		future.addListener(channelFuture ->{
			if (channelFuture.isSuccess())
				System.out.println("Server bound");
			else {
				System.err.println("Bind attempt failed");
				channelFuture.cause().printStackTrace();
			}
		});
	}
}
